import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/pages/check_tab_page.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/common/date_select.dart';
import 'package:material_collection_app/widget/common/tabbar_custom.dart';
import 'package:material_collection_app/widget/common/search_box.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';

class CheckPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<CheckPage> with SingleTickerProviderStateMixin {
  String validStartDate = '开始日期';
  String validEndDate = '结束日期';
  String keywords = '';
  List tabs = ['待盘点', '已盘点'];
  List tabsStatus = [
    {'status': '10', 'index': 0},
    {'status': '20', 'index': 1}
  ];

  List checkTypeList = ['月度盘点', '年度盘点'];
  int checkTypeIndex;
  List storeList = [];
  bool storeLoadSuccess;
  int storeIndex;
  int selectStoreId;
  List libraryList;
  bool libraryLoadSuccess;
  int libraryIndex;
  int selectLibraryId;

  TabController _tabController;
  TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: tabs.length);
    getStoreList();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  // 获取仓库列表
  getStoreList() {
    DioUtils.request("store/LibraryAddInstall",
        context: context, method: "POST", params: {}, onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          storeLoadSuccess = true;
          storeList = res['data']['store'];
        });
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 获取库区列表
  getLibraryList(id) {
    setState(() {
      libraryLoadSuccess = false;
    });

    DioUtils.request("store/LibraryLists",
        context: context,
        method: "POST",
        params: {'store_id': id, 'limit': 100000}, onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          libraryLoadSuccess = true;
          libraryList = res['data']['data'];
        });
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 重置筛选条件
  _resetScreen() {
    setState(() {
      checkTypeIndex = null;
      storeIndex = null;
      selectStoreId = null;
      libraryList = [];
      libraryLoadSuccess = false;
      libraryIndex = null;
      selectLibraryId = null;
      validStartDate = '开始日期';
      validEndDate = '结束日期';
    });
  }

  Widget _buildCardTitle(title) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(bottom: 10.w, top: 10.w),
      child: Text(
        title,
        style: TextStyle(
            color: Utils.hexToColor('#676767'), fontSize: 12, height: 1),
      ),
    );
  }

  Widget _buildTypeCard() {
    List<Widget> content = [];

    for (int i = 0; i < checkTypeList.length; i++) {
      var item = checkTypeList[i];
      content.add(InkWell(
          onTap: () {
            setState(() {
              checkTypeIndex = i;
            });
          },
          child: Container(
              width: 190.w,
              height: 76.w,
              alignment: Alignment.center,
              color:
                  Utils.hexToColor(checkTypeIndex == i ? '#E9F2FF' : '#F8F8F8'),
              child: Text(item,
                  style: TextStyle(
                      color: Utils.hexToColor(
                          checkTypeIndex == i ? '#297CFF' : '#676767'),
                      fontSize: 12,
                      fontWeight: checkTypeIndex == i
                          ? FontWeight.bold
                          : FontWeight.w500)))));
    }

    return Container(
      width: double.infinity,
      child: Wrap(
        spacing: 10.w,
        runSpacing: 10.w,
        crossAxisAlignment: WrapCrossAlignment.start,
        children: content,
      ),
    );
  }

  Widget _buildStoreCard() {
    List<Widget> content = [];

    for (int i = 0; i < storeList.length; i++) {
      var item = storeList[i];
      content.add(InkWell(
          onTap: () {
            setState(() {
              storeIndex = i;
              selectStoreId = item['store_id'];
            });
            getLibraryList(item['store_id']);
          },
          child: Container(
              width: 190.w,
              height: 76.w,
              alignment: Alignment.center,
              color: Utils.hexToColor(storeIndex == i ? '#E9F2FF' : '#F8F8F8'),
              child: Text(item['store_name'],
                  style: TextStyle(
                      color: Utils.hexToColor(
                          storeIndex == i ? '#297CFF' : '#676767'),
                      fontSize: 12,
                      fontWeight: storeIndex == i
                          ? FontWeight.bold
                          : FontWeight.w500)))));
    }

    return Container(
      width: double.infinity,
      child: Wrap(
        spacing: 10.w,
        runSpacing: 10.w,
        crossAxisAlignment: WrapCrossAlignment.start,
        children: content,
      ),
    );
  }

  Widget _buildLibraryCard() {
    List<Widget> widget = [];

    if (libraryLoadSuccess == true) {
      if (libraryList.length > 0) {
        for (int i = 0; i < libraryList.length; i++) {
          var item = libraryList[i];
          widget.add(InkWell(
              onTap: () {
                setState(() {
                  libraryIndex = i;
                  selectLibraryId = item['store_library_id'];
                });
              },
              child: Container(
                  width: 190.w,
                  height: 76.w,
                  alignment: Alignment.center,
                  color: Utils.hexToColor(
                      libraryIndex == i ? '#E9F2FF' : '#F8F8F8'),
                  child: Text(item['library_name'],
                      style: TextStyle(
                          color: Utils.hexToColor(
                              libraryIndex == i ? '#297CFF' : '#676767'),
                          fontSize: 12,
                          fontWeight: libraryIndex == i
                              ? FontWeight.bold
                              : FontWeight.w500)))));
        }
      } else {
        widget.add(storeTipsText('该仓库暂无库区'));
      }
    } else {
      if (storeIndex == null) {
        widget.add(storeTipsText('请选择仓库'));
      } else if (libraryLoadSuccess == false) {
        widget.add(storeTipsText('加载中...'));
      }
    }

    return Container(
      width: double.infinity,
      child: Wrap(
        spacing: 10.w,
        runSpacing: 10.w,
        crossAxisAlignment: WrapCrossAlignment.start,
        children: widget,
      ),
    );
  }

  Widget storeTipsText(String text) {
    return Container(
      alignment: Alignment.center,
      child: Text(
        text,
        style: TextStyle(
          color: Utils.hexToColor('#676767'),
          fontSize: 12,
        ),
      ),
    );
  }

  Widget _buildCardLine() {
    return Container(
      width: double.infinity,
      height: 1,
      margin: EdgeInsets.symmetric(vertical: 29.w),
      color: Utils.hexToColor('#FBFBFB'),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
    List<Key> keys = [checkDpdKey, checkYpdKey];

    return Scaffold(
        appBar: TopBar(
          height: 0,
        ),
        body: SafeArea(
            child: Container(
                color: Color(0xFF297CFF),
                child: Column(children: <Widget>[
                  SearchBox(
                      hintText: '名称',
                      endDrawer: false,
                      searchController: _searchController,
                      onSearch: (value) {
                        setState(() {
                          keywords = value;
                        });
                        int index = _tabController.index;
                        if (index == 0) checkDpdKey.currentState.search();
                        if (index == 1) checkYpdKey.currentState.search();
                      }),
                  Expanded(
                      child: DefaultTabController(
                          length: tabs.length,
                          initialIndex: 0,
                          child: Column(children: <Widget>[
                            TabBarCustom(
                              tabs: tabs,
                              tabController: _tabController,
                            ),
                            Expanded(
                                child: TabBarView(
                                    controller: _tabController,
                                    children: tabsStatus.map((item) {
                                      return CheckTabPage(
                                          status: item['status'],
                                          keywords: keywords,
                                          key: keys[item['index']],
                                          checkType: checkTypeIndex,
                                          storeId: selectStoreId,
                                          libraryId: selectLibraryId,
                                          startDate: validStartDate,
                                          endDate: validEndDate);
                                    }).toList()))
                          ])))
                ]))),
        endDrawer: Drawer(
            child: Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(20.w, 78.w, 20.w, 34.w),
                child: Stack(children: <Widget>[
                  Column(children: <Widget>[
                    _buildCardTitle('盘点类型'),
                    _buildTypeCard(),
                    _buildCardLine(),
                    _buildCardTitle('盘点仓库'),
                    _buildStoreCard(),
                    _buildCardLine(),
                    _buildCardTitle('盘点库区'),
                    _buildLibraryCard(),
                    _buildCardLine(),
                    Column(children: <Widget>[
                      _buildCardTitle('盘点日期'),
                      Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            DateSelect(
                              defaultDate: validStartDate,
                              resetDate: () {
                                setState(() {
                                  validStartDate = '';
                                });
                              },
                              onConfirm: (date) => {
                                setState(() {
                                  validStartDate = date;
                                })
                              },
                            ),
                            Text(
                              '—',
                              style:
                                  TextStyle(color: Utils.hexToColor('#999999')),
                            ),
                            DateSelect(
                                defaultDate: validEndDate,
                                resetDate: () {
                                  setState(() {
                                    validEndDate = '';
                                  });
                                },
                                onConfirm: (date) => {
                                      setState(() {
                                        validEndDate = date;
                                      })
                                    })
                          ])
                    ])
                  ]),
                  Align(
                      alignment: Alignment.bottomCenter,
                      child: Container(
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                            Container(
                              // margin: EdgeInsets.only(top: 70.w),
                              child: SizedBox(
                                width: 250.w,
                                height: 76.w,
                                child: ElevatedButton(
                                  onPressed: () {
                                    _resetScreen();
                                  },
                                  child: Container(
                                    margin: EdgeInsets.only(left: 16.w),
                                    child: Text(
                                      '重置',
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor:
                                        Utils.hexToColor('#FF9232'),
                                    shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.horizontal(
                                            left: Radius.circular(60.w))),
                                  ),
                                ),
                              ),
                            ),
                            Container(
                                // margin: EdgeInsets.only(top: 70.w),
                                child: SizedBox(
                                    width: 250.w,
                                    height: 76.w,
                                    child: ElevatedButton(
                                      onPressed: () {
                                        int index = _tabController.index;
                                        if (index == 0)
                                          checkDpdKey.currentState.search();
                                        if (index == 1)
                                          checkYpdKey.currentState.search();
                                        Navigator.pop(context);
                                      },
                                      child: Container(
                                        margin: EdgeInsets.only(left: 16.w),
                                        child: Text(
                                          '确定',
                                          style: TextStyle(color: Colors.white),
                                        ),
                                      ),
                                      style: ElevatedButton.styleFrom(
                                          backgroundColor: Color(0xFF297CFF),
                                          shape: RoundedRectangleBorder(
                                              borderRadius:
                                                  BorderRadius.horizontal(
                                                      right: Radius.circular(
                                                          60.w)))),
                                    )))
                          ])))
                ]))));
  }
}
